import { openDB } from 'idb'
import type { IDBPDatabase } from 'idb'

// 照片数据接口
export interface PhotoData {
  id: string
  taskId: string // 关联的任务ID
  studentId?: string // 学生ID（学生作业图片时使用）
  isCreate: boolean // true: 教师创建任务时的试卷图片, false: 学生作业图片
  thumbnail: string // 缩略图
  fullImage: string // 完整图片
  timestamp: number // 时间戳
  teacherID: string // 教师ID
  fileName?: string // 文件名
  fileSize?: string // 文件大小
  description?: string // 描述
}

// 学生照片数据接口（专门用于学生作业图片）
export interface StudentPhotoData {
  id: string
  taskId: string
  studentId: string
  thumbnail: string
  fullImage: string
  timestamp: number
  teacherID: string
  fileName?: string
  fileSize?: string
  description?: string
  status?: 'pending' | 'graded' | 'corrected' // 作业状态
}

// IndexedDB数据库结构
interface PhotosDB {
  photos: {
    key: string
    value: PhotoData
    indexes: {
      'by-task': string
      'by-student': string
      'by-teacher': string
      'by-timestamp': number
      'by-isCreate': boolean
    }
  }
}

class PhotosStorage {
  private db: Promise<IDBPDatabase<PhotosDB>>

  constructor() {
    this.db = openDB<PhotosDB>('homework-photos-system', 1, {
      upgrade(db) {
        // 创建photos对象存储（教师任务创建和学生作业图片）
        const photoStore = db.createObjectStore('photos', { keyPath: 'id' })
        photoStore.createIndex('by-task', 'taskId')
        photoStore.createIndex('by-student', 'studentId')
        photoStore.createIndex('by-teacher', 'teacherID')
        photoStore.createIndex('by-timestamp', 'timestamp')
        photoStore.createIndex('by-isCreate', 'isCreate')


      },
    })
  }

  // 初始化数据库
  async init(): Promise<void> {
    await this.db
  }

  // 保存单张照片
  async savePhoto(photo: PhotoData): Promise<string> {
    const db = await this.db
    await db.put('photos', photo)
    return photo.id
  }

  // 批量保存照片
  async savePhotos(photos: PhotoData[]): Promise<string[]> {
    const db = await this.db
    const transaction = db.transaction(['photos'], 'readwrite')
    const store = transaction.objectStore('photos')
    
    const promises = photos.map(photo => store.put(photo))
    await Promise.all(promises)
    await transaction.done
    
    return photos.map(photo => photo.id)
  }

  // 获取所有照片
  async getAllPhotos(): Promise<PhotoData[]> {
    const db = await this.db
    return db.getAll('photos')
  }

  // 根据任务ID获取试卷图片（isCreate=true）
  async getTaskPhotos(taskId: string): Promise<PhotoData[]> {
    const db = await this.db
    const allPhotos = await db.getAll('photos')
    return allPhotos.filter(photo => photo.taskId === taskId && photo.isCreate === true)
  }

  // 根据任务ID和学生ID获取学生作业图片（isCreate=false）
  async getStudentPhotos(taskId: string, studentId: string): Promise<PhotoData[]> {
    const db = await this.db
    const allPhotos = await db.getAll('photos')
    return allPhotos.filter(photo => 
      photo.taskId === taskId && 
      photo.studentId === studentId && 
      photo.isCreate === false
    )
  }

  // 根据学生ID获取所有学生作业图片
  async getPhotosByStudent(studentId: string): Promise<PhotoData[]> {
    const db = await this.db
    return db.getAllFromIndex('photos', 'by-student', studentId)
  }

  // 根据教师ID获取所有照片
  async getPhotosByTeacher(teacherID: string): Promise<PhotoData[]> {
    const db = await this.db
    return db.getAllFromIndex('photos', 'by-teacher', teacherID)
  }

  // 删除照片
  async deletePhoto(id: string): Promise<void> {
    const db = await this.db
    await db.delete('photos', id)
  }

  // 删除任务相关的所有照片
  async deleteTaskPhotos(taskId: string): Promise<void> {
    const db = await this.db
    const photos = await db.getAllFromIndex('photos', 'by-task', taskId)
    const transaction = db.transaction(['photos'], 'readwrite')
    const store = transaction.objectStore('photos')
    
    const promises = photos.map(photo => store.delete(photo.id))
    await Promise.all(promises)
    await transaction.done
  }

  // 删除学生相关的所有照片
  async deleteStudentPhotos(studentId: string): Promise<void> {
    const db = await this.db
    const photos = await db.getAllFromIndex('photos', 'by-student', studentId)
    const transaction = db.transaction(['photos'], 'readwrite')
    const store = transaction.objectStore('photos')
    
    const promises = photos.map(photo => store.delete(photo.id))
    await Promise.all(promises)
    await transaction.done
  }

  // 清空所有照片
  async clearPhotos(): Promise<void> {
    const db = await this.db
    await db.clear('photos')
  }


}

// 导出单例实例
export const photosStorage = new PhotosStorage()